package com.baibei.ebec.user.login;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.basic.module.utils.ViewExtCompat;
import com.baibei.ebec.user.BuildConfig;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.ui.AppUI;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * 登录
 * Created by ChenRui on 2017/5/5 0005 17:56.
 */
public class LoginFragment extends BasicFragment implements LoginContract.View {


    @BindView(R2.id.et_phone)
    EditText mPhoneText;

    @BindView(R2.id.et_password)
    EditText mPasswordText;

    @BindView(R2.id.btn_login)
    Button mLoginButton;

    @BindView(R2.id.btn_reset_password)
    TextView mResetPasswordButton;

    @BindView(R2.id.img_edit_delete)
    ImageView mEditDeleteView;

    @BindView(R2.id.cb_eyes)
    CheckBox mEyes;

    @BindView(R2.id.et_invitedcode)
    EditText mEtInvitedCode;

    private LoginContract.Presenter mPresenter;

    public static LoginFragment newInstance() {
        Bundle args = new Bundle();
        LoginFragment fragment = new LoginFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = inject(LoginContract.Presenter.class);
    }

    @Override
    public int getLayoutId(Bundle savedInstanceState) {
        return R.layout.fm_login;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewExtCompat.relevancePasswordVisibility(mEyes, mPasswordText);

        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mPhoneText.length() >= 11 && mPasswordText.length() >= 6) {
                    mLoginButton.setEnabled(true);
                } else {
                    mLoginButton.setEnabled(false);
                }
                mEditDeleteView.setVisibility(mPasswordText.length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };

        mPhoneText.addTextChangedListener(textWatcher);
        mPasswordText.addTextChangedListener(textWatcher);
        mEtInvitedCode.setVisibility(BuildConfig.ISSHOWINVITEDCODE ? View.VISIBLE : View.GONE);
    }


    private void showLogin() {
        mLoginButton.setEnabled(false);
        mPhoneText.setEnabled(false);
        mPasswordText.setEnabled(false);
        AppUI.loading(getContext(), getString(R.string.Signing)).setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dismissLogin();
                mPresenter.cancel();
            }
        });
    }

    @Override
    public void onDestroy() {
        mPresenter.destroy();
        super.onDestroy();
    }

    private void dismissLogin() {
        if (mLoginButton == null) return;
        mLoginButton.setEnabled(!TextUtils.isEmpty(getPassword()));
        mPhoneText.setEnabled(true);
        mPasswordText.setEnabled(true);
        AppUI.dismiss();
    }

    @OnClick(R2.id.btn_login)
    public void onLoginClick() {
        showLogin();
        mPresenter.login();
    }

    @Override
    public String getImei() {
        TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
            String imei = tm.getDeviceId();

            return imei;
        } else {

            return null;
        }
    }

    @Override
        public String getMobile() {
            return mPhoneText.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return mPasswordText.getText().toString().trim();
    }

    @Override
    public String getInvitationCode() {
        if (BuildConfig.ISSHOWINVITEDCODE) {
            return mEtInvitedCode.getText().toString();
        }
        return null;
    }

    @Override
    public void onLoginSuccess() {
        dismissLogin();
        if (!getActivity().getIntent().getBooleanExtra("justReturn", false)) {
            AppRouter.routeToMain(getActivity());
        }
        getActivity().setResult(RESULT_OK);
        getActivity().finish();
    }

    @Override
    public void onLoginFailed(String msg) {
        dismissLogin();
        AppUI.failed(getContext(), msg);

        // 如果出现登录错误，把之前的orgId清空
        if (msg.contains("密码")) {
            mPasswordText.setText("");
            mPasswordText.requestFocus();
            mLoginButton.setEnabled(false);
        }
        // 弹出键盘
        mPasswordText.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isVisible()) {
                    ViewExtCompat.showSoftInput(getContext(), mPasswordText);
                }
            }
        }, 2000);
    }

    @OnClick(R2.id.btn_reset_password)
    public void onResetClick() {
        AppRouter.routeToResetPassword(getActivity());
    }


    @OnClick(R2.id.img_edit_delete)
    public void onEditDeleteClick() {
        mPasswordText.setText("");
    }
}
